package com.etoak.controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.properties.ImageProperties;
import com.etoak.common.core.vo.ResultVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private ImageProperties imageProperties;

    @PostMapping("/image")
    public ResultVO<String> upload(MultipartFile pic) throws IOException {
        if (ObjectUtils.isEmpty(pic) || pic.isEmpty()) {
            throw new CustomException("文件不能为空");
        }
        if (!imageProperties.getTypes().contains(pic.getContentType())){
            String collect = imageProperties.getTypes().stream()
                    .map(str -> str.substring(str.lastIndexOf("/") + 1))
                    .collect(Collectors.joining("、"));
            throw new CustomException("仅支持" + collect + "类型的图片");
        }
        // 拿到图片的后缀
        String suffix = FileNameUtil.getSuffix(pic.getOriginalFilename());
        // 生成一下UUID
        String fileName = IdUtil.simpleUUID() + "." + suffix;
        // 如果不存在,则创建目录
        File uploadDir = new File(imageProperties.getUploadDir());
        if(!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        // 目标文件
        File destFile = new File(uploadDir, fileName);
        pic.transferTo(destFile);
        String path = imageProperties.getMapping().endsWith("/") ?
                imageProperties.getMapping() + fileName : imageProperties.getMapping() + "/" + fileName;
        //返回请求路径
        return ResultVO.success(path);
    }
}
